<?php

class Excursion extends CActiveRecord
{
	public function tableName()
	{
		return lfirst(__CLASS__);
	}
	
	public static function model($className = __CLASS__)
    {
    	return parent::model(lfirst(__CLASS__));
    }
    
	public function relations()
	{
		return array(
	        'attractions' => array(self::HAS_MANY, 'Attraction', 'excursionId'),
	    );
	}
    
	public function criteria($sort = 'title', $order = 'asc', $start = false, $limit = false)
	{
    	$params = array(
    		'order'  => $sort . ' ' . $order
    	);
    	
    	if ($start !== false) {
    		$params['offset'] = intval($start);
    	}
    	
    	if ($limit !== false) {
    		$params['limit'] = intval($limit);
    	}
		
		$this->getDbCriteria()->mergeWith($params);
    	
    	return $this;
	}
	
	public function saveAttractions($excursionId, $data)
	{
		Attraction::model()->deleteAll('excursionId=:excursionId', array(':excursionId' => intval($excursionId)));
    	
   		if (array_key_exists('title', $data) && count($data['title']) > 0) {
   			for($i = 0; $i < count($data['title']); $i++) {
   				$attraction = new Attraction();
   				if (strval($data['title'][$i]) != '') {
   					$attraction->excursionId = intval($excursionId);
   					$attraction->title = $data['title'][$i];
   					$attraction->description = $data['description'][$i];
   					$attraction->save();
   				}
   			}
    	}
	}
}